package com.axend.vetwavve.helper;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ServiceInfo;
import android.hardware.display.DisplayManager;
import android.hardware.display.VirtualDisplay;
import android.media.MediaRecorder;
import android.media.projection.MediaProjection;
import android.media.projection.MediaProjectionManager;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.util.Log;


import com.axend.lib_base.utils.ScreenUtils;
import com.axend.lib_base.utils.ThreadPoolUtils;
import com.axend.vetwavve.R;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author by talon, Date on 19/6/23.
 * note:
 */
public class ScreenRecordService extends Service {
    private final String NOTIFICATION_CHANNEL_ID = "com.guide.sdk.zx03c.ScreenRecordService";
    private final String NOTIFICATION_CHANNEL_NAME = "ScreenRecording";
    private final String NOTIFICATION_CHANNEL_DESC = "channel_desc";

    private final String TAG = "ScreenRecordService";
    private ExecutorService executorService = Executors.newSingleThreadExecutor();

    /**
     * 是否为标清视频
     */
    private boolean isVideoSd = true;

    private int mScreenWidth;
    private int mScreenHeight;
    private int mScreenDensity;
    private int mResultCode;
    private Intent mResultData;

    private MediaProjection mMediaProjection;
    private MediaRecorder mMediaRecorder;
    private VirtualDisplay mVirtualDisplay;

    public ScreenRecordService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i(TAG, "ScreenRecordService created");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        mResultCode = intent.getIntExtra("resultCode", 1);
        mResultData = intent.getParcelableExtra("data");

        startMediaProjectionForeground();

//        mMediaProjection = createMediaProjection();
//        if (mMediaProjection != null) {
//            mMediaRecorder = createMediaRecorder();
//            if (mMediaRecorder != null) {
//                // 必须在mediaRecorder.prepare() 之后调用，否则报错"fail to get surface"
//                mVirtualDisplay = createVirtualDisplay();
//                if (mVirtualDisplay != null) {
//                    mMediaRecorder.start();
//                    Log.i(TAG, "Screen recording started");
//                } else {
//                    Log.e(TAG, "Failed to create virtual display");
//                }
//            } else {
//                Log.e(TAG, "Failed to create media recorder");
//            }
//        } else {
//            Log.e(TAG, "Failed to create media projection");
//        }
        executorService.execute(new Runnable() {
            @Override
            public void run() {
                getScreenBaseInfo();
                startRecording();
            }
        });
        return Service.START_NOT_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i(TAG, "ScreenRecordService destroyed");
        executorService.shutdown();
        stopRecording(mMediaRecorder);

    }

    /**
     * 获取屏幕相关数据
     */
    private void getScreenBaseInfo() {
        mScreenWidth = ScreenUtils.getScreenWidth(this);
        mScreenHeight = ScreenUtils.getScreenHeight(this);
        mScreenDensity = ScreenUtils.getScreenDensityDpi(this);
    }

    private MediaProjection createMediaProjection() {
        Log.i(TAG, "Create MediaProjection");
        return ((MediaProjectionManager) getSystemService(Context.MEDIA_PROJECTION_SERVICE)).getMediaProjection(mResultCode, mResultData);
    }


    private MediaRecorder createMediaRecorder() {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss");
        Date curDate = new Date(System.currentTimeMillis());
        String curTime = formatter.format(curDate).replace(" ", "");
        String videoQuality = isVideoSd ? "SD" : "HD";

        Log.i(TAG, "Create MediaRecorder");
        MediaRecorder mediaRecorder = new MediaRecorder();
//        if(isAudio) mediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.SURFACE);
        mediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
        File appExternalDir = getExternalFilesDir(null);
        // 创建自定义子目录
        File customDir = new File(appExternalDir, "custom_video");
        if (!customDir.exists()) {
            customDir.mkdirs(); // 如果目录不存在，则创建
        }
        // 构建完整的文件路径
        String outputPath = customDir.getAbsolutePath() + File.separator+ videoQuality + curTime + ".mp4";
        mediaRecorder.setOutputFile(outputPath);
        // 判断宽高是否为奇数，setVideoSize是Native方法只能传偶数
        if (mScreenWidth % 2 != 0) {
            mScreenWidth -= 1;
        }
        if (mScreenHeight % 2 != 0) {
            mScreenHeight -= 1;
        }
        mediaRecorder.setVideoSize(mScreenWidth, mScreenHeight);  //after setVideoSource(), setOutFormat()
        mediaRecorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);  //after setOutputFormat()
//        if(isAudio) mediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);  //after setOutputFormat()
        int bitRate;
        if (isVideoSd) {
            mediaRecorder.setVideoEncodingBitRate(mScreenWidth * mScreenHeight);
//            mediaRecorder.setVideoFrameRate(30);
//            bitRate = mScreenWidth * mScreenHeight / 1000;

            // 减少资源损耗，降低帧率和比特率
            mediaRecorder.setVideoFrameRate(25);
            bitRate = mScreenWidth * mScreenHeight / 2000;
        } else {
            mediaRecorder.setVideoEncodingBitRate(5 * mScreenWidth * mScreenHeight);
            mediaRecorder.setVideoFrameRate(60); //after setVideoSource(), setOutFormat()
            bitRate = 5 * mScreenWidth * mScreenHeight / 1000;
        }
        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException | IOException e) {
            mediaRecorder.release();
            mediaRecorder = null;
        }

        return mediaRecorder;
    }

    // 文件分割逻辑
    private void startRecording() {
       try {
           mMediaProjection = createMediaProjection();
           if (mMediaProjection != null) {
               mMediaRecorder = createMediaRecorder();
               if (mMediaRecorder != null) {
                   // 必须在mediaRecorder.prepare() 之后调用，否则报错"fail to get surface"
                   mVirtualDisplay = createVirtualDisplay();
                   if (mVirtualDisplay != null) {
                       mMediaRecorder.start();
                       // 设置定时任务，每隔1小时停止当前录制并开始新的录制
                       new Timer().schedule(new TimerTask() {
                           @Override
                           public void run() {
                               stopRecording(mMediaRecorder);
                               startRecording();
                           }
                       }, 1000 * 60 * 60); // 1小时
                       Log.i(TAG, "Screen recording started");
                   } else {
                       Log.e(TAG, "Failed to create virtual display");
                   }
               } else {
                   Log.e(TAG, "Failed to create media recorder");
               }
           } else {
               Log.e(TAG, "Failed to create media projection");
           }
       }catch (Exception e){
           e.printStackTrace();
       }

    }


    private void stopRecording(MediaRecorder mediaRecorder) {
        try {
            if (mVirtualDisplay != null) {
                mVirtualDisplay.release();
                mVirtualDisplay = null;
            }
            if (mMediaRecorder != null) {
                mMediaRecorder.setOnErrorListener(null);
                mMediaRecorder.reset();
                mMediaRecorder.release();
                mMediaRecorder = null;
            }
            if (mMediaProjection != null) {
                mMediaProjection.stop();
                mMediaProjection = null;
            }
        } catch (Exception e) {
            Log.e(TAG, "Failed to stop recording: " + e.getMessage());
        }
    }


    private VirtualDisplay createVirtualDisplay() {
        Log.i(TAG, "Create VirtualDisplay");
        return mMediaProjection.createVirtualDisplay(TAG, mScreenWidth, mScreenHeight, mScreenDensity,
                DisplayManager.VIRTUAL_DISPLAY_FLAG_AUTO_MIRROR, mMediaRecorder.getSurface(), null, null);
    }

    //    private void startMediaProjectionForeground() {
//        NotificationManager NOTIFICATION_MANAGER = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//        Notification.Builder notificationBuilder = new Notification.Builder(this)
//                .setSmallIcon(R.mipmap.ic_launcher)
//                .setContentTitle("ScreenRecordService has Started");
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            String channelId = "CHANNEL_ID_MEDIA_PROJECTION";
//            NotificationChannel channel = new NotificationChannel(channelId, "ScreenRecording", NotificationManager.IMPORTANCE_HIGH);
//            NOTIFICATION_MANAGER.createNotificationChannel(channel);
//
//            notificationBuilder.setChannelId(channelId);
//        }
//        Notification notification = notificationBuilder.build();
//
//       /* if (Build.VERSION.SDK_INT >= 29) {
//            startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
//        } else {
//            startForeground(1, notification);
//        }*/
//        if (Build.VERSION.SDK_INT >=Build.VERSION_CODES.O) {
//            startForeground(1, notification);
//        }
//
//    }

//    private void startMediaProjectionForeground() {
//        NotificationManager NOTIFICATION_MANAGER = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//        Notification.Builder notificationBuilder = new Notification.Builder(this)
//                .setSmallIcon(R.mipmap.ic_launcher)
//                .setContentTitle("ScreenRecordService has Started");
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            String channelId = "CHANNEL_ID_MEDIA_PROJECTION";
//            NotificationChannel channel = new NotificationChannel(channelId, "ScreenRecording", NotificationManager.IMPORTANCE_HIGH);
//            NOTIFICATION_MANAGER.createNotificationChannel(channel);
//
//            notificationBuilder.setChannelId(channelId);
//        }
//        Notification notification = notificationBuilder.build();
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
//            startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
//        } else {
//            startForeground(1, notification);
//        }
//    }

    private void startMediaProjectionForeground() {
        NotificationManager NOTIFICATION_MANAGER = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        Notification.Builder notificationBuilder = new Notification.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle("ScreenRecordService has Started");

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            String channelId = "CHANNEL_ID_MEDIA_PROJECTION";
            NotificationChannel channel = new NotificationChannel(channelId, "ScreenRecording", NotificationManager.IMPORTANCE_HIGH);
            NOTIFICATION_MANAGER.createNotificationChannel(channel);

            notificationBuilder.setChannelId(channelId);
        }

        Notification notification = notificationBuilder.build();

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q) {
            startForeground(1, notification, ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION);
        } else {
            startForeground(1, notification);
        }

    }

//    public void startNotification() {
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//            //Call Start foreground with notification
//            Intent notificationIntent = new Intent(this, ScreenRecordService.class);
//            PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
//            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this, NOTIFICATION_CHANNEL_ID)
////                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher_foreground))
////                    .setSmallIcon(R.drawable.ic_launcher_foreground)
//                    .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
//                    .setSmallIcon(R.mipmap.ic_launcher)
//                    .setContentTitle("Starting ScreenRecordService")
//                    .setContentText("Starting ScreenRecord")
//                    .setContentIntent(pendingIntent);
//            Notification notification = notificationBuilder.build();
//            NotificationChannel channel = new NotificationChannel(NOTIFICATION_CHANNEL_ID, NOTIFICATION_CHANNEL_NAME, NotificationManager.IMPORTANCE_DEFAULT);
//            channel.setDescription(NOTIFICATION_CHANNEL_DESC);
//            NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//            notificationManager.createNotificationChannel(channel);
//            startForeground(1, notification); //必须使用此方法显示通知，不能使用notificationManager.notify，否则还是会报上面的错误
//        }
//    }
}
